package server_commands;

import static server.RLM_Server.activeConnections;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

import server.ServerSocketConnection;
import connection_modul.DatabaseConnection;

public class CHAVATARCommand extends Command {

	
	/**
	 * Konstruktor
	 * @param parameter
	 */
	public CHAVATARCommand(String parameter) {
		setCode(CHAVATAR_CMD);
		setParameter(parameter);
	}
	
	/**
	 * Vrsi se promena avatara korisnika u zatrazeni avatar.
	 * 
	 * @param connection - konekcija ka klijentu
	 * @param dbConnection - objekat za rad sa bazom
	 */
	public boolean executeCommand(ServerSocketConnection connection, DatabaseConnection dbConnection) {
		
		StringTokenizer tokenizer = new StringTokenizer(getParameter());
		
		String username = tokenizer.nextToken();
		String avatar = tokenizer.nextToken();
		
		String SQLQuery = "UPDATE tblUsers SET tblUsers.avatar = '" + avatar + "' " +
				"WHERE tblUsers.username = '" + username + "'";
		
		try {
			dbConnection.doUpdateStatement(SQLQuery);

			connection.setMessage("100 Avatar has changed");
			
			String SQLSelectQuery = "SELECT tblContacts.user_dest " +
			"FROM tblContacts " +
			"WHERE  tblContacts.user_source = '" + username + "' AND tblContacts.user_dest NOT IN " +
			"(SELECT tblBlocks.user_dest FROM tblBlocks WHERE tblBlocks.user_source = '" + username + "');";
	
			dbConnection.doStatement(SQLSelectQuery);
			
			ArrayList array = (ArrayList)dbConnection.data.clone();
		
			
			if (array.size() == 0) {
				dbConnection.doCommit();
				return true;
			}
			
			String message = "SERV_CHAVATAR " + username + " " + avatar;
			
			// Obavestava sve korisnike o logovanju aktuelnog korisnika
		
			Iterator usersIterator = array.iterator();
			
			while ( usersIterator.hasNext() ) {
				
				// username korisnika 
				String user = ((Vector)usersIterator.next()).get(0).toString();
				
				ServerSocketConnection tempConnection = activeConnections.get(user);
				
				if (tempConnection != null) {
					tempConnection.setMessage(message);
//					System.out.println("Korisnik koji se obavestava o promeni avatara usera: " + user);
				}
			}
			
			System.out.println("--> User " + username + " has just changed the avatar!");
		
		} catch (SQLException e) {
			e.printStackTrace();
			dbConnection.doRollBack();
			return false;
		}
		
		dbConnection.doCommit();
		
		return true;
	}

}
